package com.muc.plugin.dao.hander;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;

import com.muc.plugin.vo.PubEntity;

/**
 * 解析SQL查询返回的字段
 * @author lyusantu@gmail.com
 */

public class BindSQLProperty {

    private static final Logger log = LoggerFactory.getLogger(BindSQLProperty.class);

    /**
     * 解析 数据库查询返回集合
     *
     * @param rs
     * @return
     */
    public static List<PubEntity> findBySQL(ResultSet rs) {
        List<PubEntity> list = new ArrayList<PubEntity>();
        try {
            String column = null;
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                PubEntity pm = new PubEntity();
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                for (int x = 1; x <= columnCount; x++) {
                    column = rsmd.getColumnName(x);
                    hashMap.put(column, rs.getObject(column));
                }
                pm.setHashMap(hashMap);
                list.add(pm);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("bind SQL property error");
        }
        return null;
    }

    /**
     * 解析实体 把属性绑定到 iq
     *
     * @param ent
     * @param iq
     * @return
     */
    public static IQ bindXmlProperty(PubEntity ent, IQ iq) {
        Iterator<String> cols = ent.getColumnNames();
        if (cols == null) {
            return iq;
        }
        while (cols.hasNext()) {
            String colName = cols.next();
            try {
                Object colValue = ent.getColumnValue(colName);
                if (colValue == null || StringUtils.isEmpty(String.valueOf(colValue)))
                    iq.getChildElement().addElement(colName);
                else
                    iq.getChildElement().addElement(colName).addText(String.valueOf(colValue));
            } catch (Exception e) {
                e.printStackTrace();
                log.error("bind property key error:" + colName);
            }
        }
        return iq;
    }

}
